package com.mavenq.fly.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext ctx;

    private static class ApplicationContextSetter {
        static void setContext(final ApplicationContext ctx) {
            SpringContextUtils.ctx = ctx;
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextSetter.setContext(applicationContext);
    }

    public static <T> T getBean(String name) throws BeansException {
        return (T) ctx.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return ctx.getBean(clazz);
    }

    public static <T> Map<String, T> getBeans(Class<T> clazz) throws BeansException {
        return ctx.getBeansOfType(clazz);
    }

}
